﻿using Dapper;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using System.Xml.Linq;
using WebApplication1.Entity;
using yunbo.Model.SSM;

namespace yunbo.Repositorys.SSMRepositorys
{
    public class MenuRepository
    {
        public string data = "Data Source=121.37.93.71;Initial Catalog=FanXingMES;User ID=sa;Password=geili@2025;";

        public List<MenuNode> GetTree()
        {
            using (SqlConnection connection = new SqlConnection(data))
            {
                string sql = "SELECT * FROM menu";
                List<Menu> menus = connection.Query<Menu>(sql).ToList(); // 使用 ToList() 获取所有菜单  
                return GetTreeData(menus, 0); // 获取根节点  
            }
        }

        public List<MenuNode> GetTreeData(List<Menu> menus, int pid)
        {
            List<MenuNode> menuNodes = new List<MenuNode>();

            // 从菜单列表中筛选出父级ID匹配的菜单项  
            var childMenus = menus.Where(m => m.menu_pid == pid).ToList();

            foreach (var menu in childMenus)
            {
                MenuNode node = new MenuNode
                {
                    menu_id = menu.menu_id,
                    menu_name = menu.menu_name,
                    menu_url = menu.menu_url,
                    menu_icon = menu.menu_icon,
                    menu_state=menu.menu_state,
                    menu_create_by = menu.menu_create_by,
                    menu_create_time = menu.menu_create_time,
                    menu_update_by = menu.menu_update_by,
                    menu_update_time = menu.menu_update_time,
                    Children = GetTreeData(menus, menu.menu_id) // 递归获取子节点  
                };
                menuNodes.Add(node);
            }

            return menuNodes;
        }

        public string GetMenuName(int menu_id)
        {
            using (SqlConnection connection = new SqlConnection(data))
            {
                connection.Open();
                // 修改 SQL 查询语句，只查询菜单名称
                string sql = "SELECT menu_name FROM menu WHERE menu_id = @menu_id";
                // 创建 SqlCommand 对象
                using (SqlCommand command = new SqlCommand(sql, connection))
                {
                    // 添加参数
                    command.Parameters.AddWithValue("@menu_id", menu_id);
                    // 执行查询并获取结果
                    object result = command.ExecuteScalar();
                    // 如果结果不为 null，将其转换为字符串返回；否则返回空字符串
                    return result != null ? result.ToString() : string.Empty;
                }
            }
        }
    }
}
